package com.runa.monitor.platinterface.netservice.equipment.dtu;

import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.dto.Node;
import com.runa.monitor.platinterface.backwork.function.TaskFunction;
import com.runa.monitor.platinterface.netservice.equipment.dtu.point.ModbusPoints;
import com.runa.protocol.dto.ModbusPoint;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.netservice.dtu.DtuResponse;
import com.runa.rccprotocol.netservice.dtu.ModbusRtuResponse;
import com.runa.rccprotocol.netservice.modbus.ModbusRequest;
import lombok.extern.slf4j.Slf4j;
import java.util.*;

/**
 * 2024/8/26 9:31
 * zhangYB
 */
@Slf4j
public class HdDtuDriver extends WirelessDtuDriver {

    private DtuTaskFunction dtuTaskFunction;

    public HdDtuDriver(String serial, Integer timeout, ModbusPoints points) {
        super(serial, timeout, points);
    }

    public void readPoints(Node node, TaskFunction function) {
        int slaveId = node.getIndex();
        List<List<ModbusPoint>> sections = allPoints.getSections();
        dtuTaskFunction = new DtuTaskFunction(function, node, sections.size());
        for (int i = 0; i < sections.size(); i++) {
            if (dtuTaskFunction.canRequest()) {
                List<ModbusPoint> modbusPoints = sections.get(i);
                ModbusRequest modbusRequest = new ModbusRequest(serial());
                modbusRequest.setModbusPoints(modbusPoints);
                modbusRequest.readHdModbusData(slaveId);
                dtuTaskFunction.addRequest(modbusRequest);
                sendRequest(modbusRequest, dtuTaskFunction);
            }
        }
    }


    @Override
    public void receiveDtuResponse(DtuResponse dtuResponse) {
        log.debug("dtuResponse: {}", JSON.toJSONString(dtuResponse));
        if (dtuResponse instanceof ModbusRtuResponse) {
            ModbusRtuResponse modbusRtuResponse = (ModbusRtuResponse)dtuResponse;
            log.debug("modbusRtuResponse data: {}", ByteUtil.byteToHexString(modbusRtuResponse.getModbusResponse().getData()));
            dtuTaskFunction.addResponse(modbusRtuResponse);
            mockUnlock();
            if (dtuTaskFunction.isTailFrame()) {
                dtuTaskFunction.finish();
            }
        }
    }




}
